// type answer = {
//     name: string;
//     age:number
//     email ?:string
//     interests:("运动"|"音乐"|"阅读")[]
// }
// function registerUser(name: string, age: number, email ?: string,interests ?:("运动"|"音乐"|"阅读")[],):answer{
//     if (age < 18 ){
//         throw new Error("未成年");
//     }
//     return {
//         name: name,
//         age: age,
//         email : email||" ",
//         interests: interests||[],
//     }
// }
// const user1 = registerUser("张三", 78, "zhang@example.com", ["运动","阅读"]);
// const user2 = registerUser("李四", 90);
// console.log(user1);
// console.log(user2);

// type Product={
//     id:number,
//     name:string,
//     price:number,
// }

// type CartItem={
//     product:Product,
//     quantity:number
// }

// let cartItems : CartItem[]=[];
// function addToCart(cart: CartItem[], product: Product, quantity: number): CartItem[] {
//   let aa:CartItem={product, quantity}
//   if(aa.quantity<0){
//     throw new Error("数量不能小于0");
//   }
//   cartItems.push(aa);
//   return cartItems;
// }
// function calculateTotal(cart: CartItem[]): number {
//   let total:number = 0;
//   for (let i = 0; i < cart.length; i++) {
//       total+=cart[i].product.price*cart[i].quantity;
//   }
//   return total;
// }

// const products: Product[] = [
//   {id: 1, name: "手机", price: 2999},
//   {id: 2, name: "耳机", price: 399}
// ];

// let cart: CartItem[] = [];
// cart = addToCart(cart, products[0], 2);
// cart = addToCart(cart, products[1], 1);

// console.log(calculateTotal(cart));

// type data={
//   id:number
//   name:string
// }
// type errors={
//   message:string
// }

// function handleResponse<data,error>(arg:data|error):data|error{
//   if (isError(arg)){
//     throw new Error ((arg).message)
//   }else{
//     return arg
//   }
// }

// function isError(arg:any):arg is errors{
//   return arg instanceof Error
// }

// const successRes = { data: { id: 1, name: "测试产品" } };
// // const product = handleResponse(successRes); // 应返回 { id: 1, name: "测试产品" }

// const errorRes = { error: "未找到资源" };
// const product =handleResponse(errorRes); // 应抛出错误 "未找到资源"
// // 错误情况

// console.log(product);


//4
// interface Shape {
//   type: "circle" | "rectangle";
//   calculateArea(): number;
// }

// class Circle implements Shape {
//     type: "circle";
//     radius: number;
//     constructor(radius: number,type: "circle") {
//         this.radius = radius;  
//         this.type = type;
//     }
//     calculateArea(): number {
//         return Math.PI * this.radius * this.radius;
//     }
// }

// class Rect implements Shape {
//     type: "rectangle";
//     width: number;
//     height:number;
//     constructor(type:"rectangle",width: number,height:number) {
//         this.width = width;
//         this.height = height;
//         this.type = type;
//     }
//     calculateArea(): number {
//         return this.width * this.height;
//     }
// }

// function createShape(type: "circle" | "rectangle", ...args: number[]): Shape{
//     if (type=="circle")
//         return new Circle(args[0],"circle");
//     return new Rect("rectangle",args[0],args[1]);
// }

// const circle = createShape("circle", 5); // 半径5的圆
// console.log(circle.calculateArea()); // ≈78.54

// const rect = createShape("rectangle", 4, 6); // 4x6的矩形
// console.log(rect.calculateArea()); // 24

//5
type SerializablePrimitive = string | number | boolean | null;
type SerializableObject = { [key: string]: Serializable } & { toJSON?: never };
type SerializableArray = Array<Serializable>;

type Serializable = 
  | SerializablePrimitive
  | SerializableObject
  | SerializableArray;

class TypedLocalStorage<T extends Serializable> {
  private getStorageKey(key: string): string {
    return `typed:${key}`;
  }

  private getExpiryKey(key: string): string {
    return `expiry:${key}`;
  }

  setItem(key: string, value: T, expires?: Date): void {
    try {
      const storageKey = this.getStorageKey(key);
      localStorage.setItem(storageKey, JSON.stringify(value));
      
      if (expires) {
        const expiryKey = this.getExpiryKey(key);
        localStorage.setItem(expiryKey, expires.toISOString());
      } else {
        localStorage.removeItem(this.getExpiryKey(key));
      }
    } catch (error) {
      console.error("Failed to store value:", error);
      throw new Error("Value is not serializable");
    }
  }

  getItem(key: string): T | null {
    const storageKey = this.getStorageKey(key);
    const expiryKey = this.getExpiryKey(key);
    
    const expiryString = localStorage.getItem(expiryKey);
    if (expiryString) {
      const expiryDate = new Date(expiryString);
      if (expiryDate < new Date()) {
        localStorage.removeItem(storageKey);
        localStorage.removeItem(expiryKey);
        return null;
      }
    }
    
    const item = localStorage.getItem(storageKey);
    if (item === null) return null;
    
    try {
      return JSON.parse(item) as T;
    } catch (error) {
      console.error("Failed to parse stored value:", error);
      return null;
    }
  }
}
const userStorage = new TypedLocalStorage<{name: string, age: number}>();

// 存储
userStorage.setItem("user", {name: "张三", age: 25});

// 读取
const user = userStorage.getItem("user"); // 类型为 {name: string, age: number} | null

// // 错误示例
// userStorage.setItem("data", new Date()); // 应报错：Date不可序列化